package com.fingard.dsp.bank.directbank.cfcc01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.IpHelper;
import com.fingard.net.WebRequest;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

/**
 * @author Parker on 2019-08-08.
 * @version 1.0
 */
public class CFCC01Base extends DirectBase {
    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);
    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    //http格式
    protected String[] sendToBank(String pReqStr) throws Exception{
        WriteBankLogStep2(pReqStr);
        String[] retStr = new String[]{"",""};
        String tmpAddrUrl = bankFront.serverURL;
        WriteBankLogLn("2.提交银行的地址：" + tmpAddrUrl);
        WebRequest tmpWebRequest = new WebRequest(tmpAddrUrl);
        tmpWebRequest.setConnectTimeout(100000);
        tmpWebRequest.setRequestProperty("Method", "POST");
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        tmpWebRequest.setRequestProperty("connection", "close");//设置连接状态

        byte[] tmpUpBytes = pReqStr.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());

        WriteBankLogStep3("3.银行返回的报文："+retStr[1]);
        return retStr;
    }

    protected void writeCommonHeader(XmlTextWriter xmlTextWriter, CFCC01Header bankHeader){
        xmlTextWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
        xmlTextWriter.writeStartElement("TRANSACTION");
        xmlTextWriter.writeStartElement("HEADER");
        xmlTextWriter.writeElementString("REQ_TYPE", bankHeader.transCode);//交易代码
        xmlTextWriter.writeElementString("REQ_TIME", Format.DateTime14Format.format(new Date()));//请求时间
        xmlTextWriter.writeElementString("OPER_ID", bankFront.operator);//用户ID
        String localIP = IpHelper.getLocalHostIp();
        xmlTextWriter.writeElementString("REQ_IP", localIP);//本地机器IP
        xmlTextWriter.writeElementString("REQ_INDEX", localIP+getQryTransID());//本地机器IP + 时间戳
        xmlTextWriter.writeEndElement();
    }




}
